/**
 * created by 江心才子, 2019/8/6
 * Copyright (c) 2019, 270628297@qq.com All Rights Reserved.
 * #                   *********                            #
 * #                  ************                          #
 * #                  *************                         #
 * #                 **  ***********                        #
 * #                ***  ****** *****                       #
 * #                *** *******   ****                      #
 * #               ***  ********** ****                     #
 * #              ****  *********** ****                    #
 * #            *****   ***********  *****                  #
 * #           ******   *** ********   *****                #
 * #           *****   ***   ********   ******              #
 * #          ******   ***  ***********   ******            #
 * #         ******   **** **************  ******           #
 * #        *******  ********************* *******          #
 * #        *******  ******************************         #
 * #       *******  ****** ***************** *******        #
 * #       *******  ****** ****** *********   ******        #
 * #       *******    **  ******   ******     ******        #
 * #       *******        ******    *****     *****         #
 * #        ******        *****     *****     ****          #
 * #         *****        ****      *****     ***           #
 * #          *****       ***        ***      *             #
 * #            **       ****        ****                   #
 */
package com.wyl.home.video

import android.view.View
import androidx.databinding.ObservableArrayList
import androidx.lifecycle.MutableLiveData
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.toDisposables
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import com.wyl.base.*
import com.wyl.base.bean.ListData
import com.wyl.base.bean.RoleData
import com.wyl.base.bean.VideoData
import com.wyl.libbase.base.BaseViewModel
import com.wyl.libbase.utils.KLog
import io.reactivex.Observable

/**
 * 项目名称：ShortVideo
 * 创建人：江心才子
 * 创建时间：2019-08-06 10:09
 * 内容描述：
 * 修改说明：
 */
class VideoDetailViewModel : BaseViewModel() {
    val shangSuccess: MutableLiveData<String> by lazy { MutableLiveData<String>() }

    val dataSource = ObservableArrayList<Any>()
    val roleData = ObservableArrayList<RoleData>()
    val videoNoData = ObservableArrayList<VideoData>()
    var videoData = MutableLiveData<VideoData>()
    val videoPlayer: MutableLiveData<VideoData> by lazy { MutableLiveData<VideoData>() }

    fun description(): String {
        val no = videoNoData.last()?.number ?: "0"
        return videoData.value?.run {
            "热度$popularity/$type/更新至${no}集 共${episode}集"
        } ?: ""
    }

    //    /**
//     * noid 无用参数
//     */
    fun loadDetail(videoid: String, noid: String, new: Boolean) = loadDetailNoData(videoid)
        .doOnSubscribe { loading.value = true }
        .doFinally { loading.value = false }
        .flatMap {
            if (it.code == 0) {
                videoNoData.addAll(it.data)
            } else {
                videoNoData.add(VideoData().apply { number = "0" })
            }
            loadDetailData(videoid)
        }
        .map { it.data }
        .flatMap { data ->
            videoData.value = data.video
            data.appRole?.apply {
                forEachIndexed { index, data ->
                    if (index > 3) {
                        data.showPicture = View.GONE
                    }
                }
                roleData.addAll(this)
                dataSource.add(this@VideoDetailViewModel)
//                data.appRoleSpeak?.apply { dataSource.addAll(this) }
            }

            when {
                new -> Observable.just("new")
                noid.isEmpty() -> loadHistoryData(videoid).map {
                    val video = it.data
                    videoPlayer.value = video
                    video.appVideoId
                }
                else -> Observable.just(noid)
            }
        }.subscribe(
            { data ->
                if (data == "new") {
                    videoPlayer.value =
                        videoNoData.last { it.playType == 1 }.apply { playing = true }
                } else {
                    val videoNo = videoNoData.find { data == it.appVideoId }
                    videoNo?.apply {
                        playing = true
                        if (noid.isNotEmpty()) videoPlayer.value = this
                    }
                }
            }, {
                it.printStackTrace()
                videoPlayer.value = videoNoData.first().apply { playing = true }
            }
        ).toDisposables(disposables)

    fun loadRoleSpeakData(id: String) =
        OkGo.post<BaseResponse<List<RoleData>>>(RoleSpeak)
            .params("id", id)
            .converter(object : JsonConvert<BaseResponse<List<RoleData>>>() {})
            .adapt(ObservableBody<BaseResponse<List<RoleData>>>())
            .map { it.data }
            .subscribe({ data ->
                dataSource.removeAll { it is RoleData }
                dataSource.addAll(data)
            }, {
                it.printStackTrace()
            }).toDisposables(disposables)

    private fun loadDetailData(id: String): Observable<BaseResponse<ListData>> =
        OkGo.post<BaseResponse<ListData>>(DETAIL)
            .params("appUserId", ACacheHelper.id)
            .params("id", id)
            .converter(object : JsonConvert<BaseResponse<ListData>>() {})
            .adapt(ObservableBody<BaseResponse<ListData>>())

    private fun loadDetailNoData(id: String): Observable<BaseResponse<List<VideoData>>> =
        OkGo.post<BaseResponse<List<VideoData>>>(DETAIL_NO)
            .params("id", id)
            .converter(object : JsonConvert<BaseResponse<List<VideoData>>>() {})
            .adapt(ObservableBody<BaseResponse<List<VideoData>>>())

    private fun loadHistoryData(id: String): Observable<BaseResponse<VideoData>> =
        OkGo.post<BaseResponse<VideoData>>(DetailHistoryNew)
            .params("appUserId", ACacheHelper.id)
            .params("appFolkOperaId", id)
            .converter(object : JsonConvert<BaseResponse<VideoData>>() {})
            .adapt(ObservableBody<BaseResponse<VideoData>>())

    fun collect() {
        if (videoData.value?.status == 1) {
            // 收藏
            OkGo.post<BaseResponse<Any>>(CommonCollect)
                .params("appUserId", ACacheHelper.id)
                .params("appFolkOperaId", videoData.value?.appFolkOperaId)
                .converter(object : JsonConvert<BaseResponse<Any>>() {})
                .adapt(ObservableBody<BaseResponse<Any>>())
                .doOnSubscribe { loading.value = true }
                .doFinally { loading.value = false }
                .subscribe(
                    { data ->
                        toast.value = data.msg
                        videoData.value?.status = 2
                    }, {
                        onError(it)
                        it.printStackTrace()
                    }
                ).toDisposables(disposables)
        } else {
            // 取消收藏
            OkGo.post<BaseResponse<Any>>(CommonCancelCollect)
                .params("appUserId", ACacheHelper.id)
                .params("appFolkOperaId", videoData.value?.appFolkOperaId)
                .converter(object : JsonConvert<BaseResponse<Any>>() {})
                .adapt(ObservableBody<BaseResponse<Any>>())
                .doOnSubscribe { loading.value = true }
                .doFinally { loading.value = false }
                .subscribe(
                    { data ->
                        toast.value = data.msg
                        videoData.value?.status = 1
                    }, {
                        onError(it)
                        it.printStackTrace()
                    }
                ).toDisposables(disposables)
        }
    }

    fun shangVideo(tiantong: Int) {
        OkGo.post<BaseResponse<Any>>(DetailVideoReward)
            .params("appUserId", ACacheHelper.id)
            .params("appFolkOperaId", videoData.value?.appFolkOperaId)
            .params("goldcoin", tiantong)
            .params("type", 1)
            .params("appFolkOperaName", videoData.value?.operaName)
            .converter(object : JsonConvert<BaseResponse<Any>>() {})
            .adapt(ObservableBody<BaseResponse<Any>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe(
                { data ->
                    userData?.gold = data.totalPage.toString()
                    shangSuccess.value = "成功"
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)
    }

    fun shangRole(tiantong: Int, id: String) {
        OkGo.post<BaseResponse<Any>>(DetailRoleReward)
            .params("appUserId", ACacheHelper.id)
            .params("appFolkOperaId", videoData.value?.appFolkOperaId)
            .params("goldcoin", tiantong)
            .params("appRoleId", id)
            .params("type", 2)
            .params("appFolkOperaName", videoData.value?.operaName)
            .converter(object : JsonConvert<BaseResponse<Any>>() {})
            .adapt(ObservableBody<BaseResponse<Any>>())
            .subscribe(
                { data ->
                    userData?.gold = data.totalPage.toString()
                    shangSuccess.value = "成功"
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)
    }

    fun addHistory(remarks: Int, currentTime: Int) {
        if (videoPlayer.value == null) {
            return
        }
        val disposable = OkGo.post<BaseResponse<Any>>(DetailAddRecords)
            .params("appUserId", ACacheHelper.id)
            .params("appVideoId", videoPlayer.value?.appVideoId)
            .params("remarks", remarks)
            .params("currentTime", currentTime)
            .converter(object : JsonConvert<BaseResponse<Any>>() {})
            .adapt(ObservableBody<BaseResponse<Any>>())
            .subscribe(
                {
                    KLog.d("addHistory success. remarks=$remarks, currentTime=$currentTime")
                }, {
                    it.printStackTrace()
                }
            )
    }

    var bbtList = emptyList<Int>()
    var tiantongList = emptyList<Int>()
    var radio = 1

    fun loadTiantong() {
        OkGo.post<BaseResponse<List<Map<String, Int>>>>(DetailRoleNumber)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, Int>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, Int>>>>())
            .map { it.data }
            .subscribe(
                { data ->
                    bbtList = data.map { it["number"]!! }
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)

        OkGo.post<BaseResponse<List<Map<String, Int>>>>(DetailNumber)
            .converter(object : JsonConvert<BaseResponse<List<Map<String, Int>>>>() {})
            .adapt(ObservableBody<BaseResponse<List<Map<String, Int>>>>())
            .map { it.data }
            .subscribe(
                { data ->
                    tiantongList = data.map { it["number"]!! }
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)

        OkGo.post<BaseResponse<Map<String, Int>>>(DetailRatio)
            .converter(object : JsonConvert<BaseResponse<Map<String, Int>>>() {})
            .adapt(ObservableBody<BaseResponse<Map<String, Int>>>())
            .map { it.data }
            .subscribe(
                { data ->
                    radio = data["number"]!!
                }, {
                    onError(it)
                    it.printStackTrace()
                }
            ).toDisposables(disposables)
    }

}